package com.wise.service.cms.content.uploadresource;

import com.microsoft.azure.storage.StorageException;
import com.microsoft.azure.storage.blob.BlobProperties;
import com.microsoft.azure.storage.blob.CloudBlobContainer;
import com.microsoft.azure.storage.blob.CloudBlockBlob;
import com.wise.config.CloudBlockBlobCreator;
import com.wise.entities.content.Resource;
import com.wise.framework.dao.SqlSelect;
import com.wise.framework.daomodel.DaoList;
import com.wise.framework.daomodel.DaoOne4Update;
import com.wise.framework.daomodel.DaoSave;
import com.wise.framework.exception.Excep;
import com.wise.summer.v1.cms.content.uploadresource.UpdateUploadResource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.summerframework.model.SummerService;
import org.summerframework.model.SummerServiceBean;

import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.List;

import static com.wise.model.content.ContentErrMsgs.Err_000100140011;
import static com.wise.model.content.ContentErrMsgs.Err_000100140019;
import static com.wise.model.content.ContentErrMsgs.Err_100100000004;

/**
 * @author Pitaya
 * @date 2019-11-13
 */

@Service
@SummerService
@Slf4j
public class UpdateUploadResourceService implements SummerServiceBean<UpdateUploadResource> {
//    @Autowired
//    CloudBlockBlobCreator blockBlobCreator;
    @Autowired
    CloudBlockBlobCreator blockBlobCreator;
    @Override
    public void sum(UpdateUploadResource summer) {
        //文件名称不可重复
        checkDuplicateName(summer.getFileName(), summer.getId());
        Resource resource = DaoOne4Update.s(Resource.class, summer.getId(), Err_100100000004);
        CloudBlockBlob blockBlob;
        try {
            blockBlob = blockBlobCreator.getBlockBlob(resource.getResourceName(), URLEncoder.encode(summer.getFileName()));

            if (blockBlob.exists()) {
                blockBlob.downloadAttributes();
                blockBlob.getProperties().setContentType("application/octet-stream");
                blockBlob.getProperties().setContentDisposition("attachment; filename="+URLEncoder.encode(summer.getFileName()));
                this.uploadProperties(null, blockBlob, null, 0L);
            }
            log.info("block 的唯一标示 " + blockBlob.hashCode());
        } catch (URISyntaxException | StorageException e) {
            log.error(e.getMessage(), e);
            throw Excep.le(Err_000100140019);
        }

        resource.setUploadTime(summer.getUploadTime());
        resource.setOriginResourceName(summer.getFileName());
        resource.setDescribe(summer.getDescribe());
        DaoSave.s(resource);

        summer.setSummerResult(true);
    }

    /**
     * 文件名称不可重复
     */
    private void checkDuplicateName(String fileName, String id) {
        SqlSelect queryForFile = SqlSelect.selec(Resource._id).fromClassName(Resource.class).
                eq(Resource._originResourceName, fileName);
        List<Resource> resources = DaoList.s(Resource.class, queryForFile);
        if(resources.isEmpty()){
            return;
        }
        if(resources.size() > 1){
            throw Excep.le(Err_000100140011);
        }
        if(!resources.get(0).getId().equals(id)){
            throw Excep.le(Err_000100140011);
        }
    }

    private void uploadProperties(Integer blockNum, CloudBlockBlob blockBlob, InputStream fileInputStream, long size) {
        try {
//            String blockId = String.format("%05d", blockNum);
//            String blockIdEncoded = Base64.getEncoder().encodeToString(blockId.getBytes());
            blockBlob.uploadProperties();
//            blockBlob.uploadBlock(blockIdEncoded, fileInputStream, fileInputStream.available());
//            log.info("blockIdEncoded" + blockIdEncoded);
//            log.info("[File Block Upload Success, blockId={}, size={}, {}] ", blockId, size, blockBlob.getSnapshotID());
//            return blockBlob.getUri().toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw Excep.le(Err_000100140019);
        }
    }
}
